package com.century.sjt.widget.picture;

import android.app.Dialog;
import android.app.Service;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.ImageRequest;
import com.android.volley.toolbox.Volley;
import com.century.sjt.R;
import com.century.sjt.activity.ShareFriendActivity;
import com.century.sjt.activity.ShareShopActivity;
import com.century.sjt.photoview.PhotoViewAttacher;
import com.century.sjt.photoview.PhotoViewAttacher.OnPhotoTapListener;
import com.century.sjt.util.Constant;
import com.century.sjt.util.FileUtil;
import com.century.sjt.util.TextDialog;
import com.century.sjt.util.TipUtil;
import com.century.sjt.widget.picture.universalimageloader.core.ImageLoader;
import com.century.sjt.widget.picture.universalimageloader.core.assist.FailReason;
import com.century.sjt.widget.picture.universalimageloader.core.listener.SimpleImageLoadingListener;
import com.easemob.EMCallBack;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMMessage;
import com.easemob.chat.ImageMessageBody;

import java.io.File;

//import com.century.sjt.library.third.universalimageloader.core.ImageLoader;
//import com.century.sjt.library.third.universalimageloader.core.assist.FailReason;
//import com.century.sjt.library.third.universalimageloader.core.listener.SimpleImageLoadingListener;
//import com.century.sjt.library.widget.photoview.PhotoViewAttacher;
//import com.century.sjt.library.widget.photoview.PhotoViewAttacher.OnPhotoTapListener;

/**
 * 单张图片显示Fragment
 *
 * @author 曾繁添
 * @version 1.0
 */
public class PictureItemFragment extends Fragment {

    /**
     * 当前Fragment渲染的视图View
     **/
    private View mContextView = null;
    private PictureBean picture;
    private ImageView mImageView;
    private ProgressBar mPprogressBar;
    private PhotoViewAttacher mAttacher;
    private Vibrator vibrator;
    private String filePath = "";

    private Dialog dialog;
    private LinearLayout llBackground;

    private TextView tvFriend;
    private TextView tvBusiness;
    private TextView tvSave;
    private String username;
    private String shopCount;
    private RequestQueue mQueue;

    private Handler mHandler;
    private TextDialog textDialog;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        mQueue = Volley.newRequestQueue(getActivity());
        picture =
                getArguments() != null
                        ? (PictureBean) getArguments().getSerializable("picture")
                        : new PictureBean();

        username =
                getArguments() != null
                        ? (String) getArguments().getString("username")
                        : new String();
        shopCount =
                getArguments() != null
                        ? (String) getArguments().getString("shopCount")
                        : new String();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // 渲染视图View
        if (null == mContextView) {
            mHandler = new Handler() {
                @Override
                public void handleMessage(Message msg) {
                    switch (msg.what) {
                        case 1:
                            TipUtil.showToast("发送成功", getActivity(), 1);
                            break;
                        case 2:
                            TipUtil.showToast("发送失败", getActivity(), 1);
                            break;
                    }
                }
            };
            mContextView = inflater.inflate(R.layout.common_picture_item, container, false);
            mPprogressBar = (ProgressBar) mContextView.findViewById(R.id.loading);
            mImageView = (ImageView) mContextView.findViewById(R.id.image);
            vibrator = (Vibrator) getActivity().getSystemService(Service.VIBRATOR_SERVICE);
            initDialog();//初始化dialog
            initLoadingDialog();//初始化dialog
            mAttacher = new PhotoViewAttacher(mImageView);
            mAttacher.setOnPhotoTapListener(new OnPhotoTapListener() {

                @Override
                public void onPhotoTap(View arg0, float arg1, float arg2) {
//          getActivity().finish();
                }
            });
            mAttacher.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    TipUtil.log("longClick_imageUrl", filePath, 1);
                    dialog.show();
                    vibrator.vibrate(new long[]{0, 50}, -1);
                    return true;
                }
            });

        }
        return mContextView;
    }

    private void initLoadingDialog() {
        textDialog = new TextDialog(getActivity());

    }

    private void initDialog() {
        dialog = new Dialog(getActivity(), R.style.Transparent);
        dialog.setContentView(R.layout.dialog_photoview);
        llBackground = (LinearLayout) dialog.findViewById(R.id.ll_background);
        tvFriend = (TextView) dialog.findViewById(R.id.tv_friend);
        tvBusiness = (TextView) dialog.findViewById(R.id.tv_business);
        tvSave = (TextView) dialog.findViewById(R.id.tv_save);
        llBackground.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        tvFriend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                Intent intent = new Intent(getActivity(),ShareFriendActivity.class);
                intent.putExtra("imageUrl",filePath);
                startActivity(intent);
            }
        });
        tvBusiness.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                switch (shopCount){
                    case Constant.SHOP_COUNT_ONE:
//                      String picId = filePath.substring(filePath.length() - 22, filePath.length() - 4);//获取图片Id的方式(旧)
                        String[] strImageUrl = filePath.split("/");//获取图片Id的方式
                        String picId = strImageUrl[strImageUrl.length-1];
                        TipUtil.log("picId", picId, 1);
                        saveImage(picId, filePath, mQueue);
                        break;
                    case Constant.SHOP_COUNT_LIST:
                        dialog.dismiss();
                        Intent intent = new Intent(getActivity(),ShareShopActivity.class);
                        intent.putExtra("imageUrl",filePath);
                        startActivity(intent);
                        break;
                    default:
                        break;
                }
            }
        });
        tvSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String[] strImageUrl = filePath.split("/");//获取图片Id的方式
                String picId = strImageUrl[strImageUrl.length-1];
                TipUtil.log("picId", picId, 1);
                String strPicId = picId.split("\\.")[0];//获取图片Id的方式
                downLoadImage(strPicId, filePath, mQueue);
            }
        });
    }

    /**
     * 发送图片给商家或者好友
     * @param picId
     * @param picUrl
     * @param mQueue
     */
    private void saveImage(final String picId, final String picUrl, RequestQueue mQueue) {
        FileUtil.createImageDir();
        File file = new File(Constant.CAMERA_PICTURE_PATH, picId);
        if (!file.exists()) {//文件不存在，下载下来
            ImageRequest imageRequest = new ImageRequest(picUrl, new Response.Listener<Bitmap>() {
                @Override
                public void onResponse(Bitmap bitmap) {
                    FileUtil.saveImg(bitmap, picId);                //保存图片
                    sendImage(Constant.CAMERA_PICTURE_PATH + picId);
                }
            }, 0, 0, ImageView.ScaleType.CENTER_CROP, Bitmap.Config.RGB_565, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    TipUtil.showToast("图片下载失败！", getActivity(), 1);
                    TipUtil.log("图片下载失败", volleyError.toString(), 1);
                }
            });
            mQueue.add(imageRequest);
        } else {
            sendImage(Constant.CAMERA_PICTURE_PATH + picId);
        }
    }

    /**
     * 保存图片到本地
     * @param picId
     * @param picUrl
     * @param mQueue
     */
    private void downLoadImage(final String picId, final String picUrl, RequestQueue mQueue) {
        FileUtil.createImageDir();
        File file = new File(Constant.DOWNLOAD_PICTURE_PATH, picId);
        if (!file.exists()) {//文件不存在，下载下来
            ImageRequest imageRequest = new ImageRequest(picUrl, new Response.Listener<Bitmap>() {
                @Override
                public void onResponse(Bitmap bitmap) {
                    FileUtil.savedownLoadImg(bitmap, picId,getActivity());                //保存图片
                    TipUtil.showToast("图片保存路径："+ Constant.DOWNLOAD_PICTURE_PATH, getActivity(), 1);
                    dialog.dismiss();
                }
            }, 0, 0, ImageView.ScaleType.CENTER_CROP, Bitmap.Config.RGB_565, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    TipUtil.showToast("图片下载失败！", getActivity(), 1);
                    TipUtil.log("图片下载失败", volleyError.toString(), 1);
                    dialog.dismiss();
                }
            });
            mQueue.add(imageRequest);
        } else {
            TipUtil.showToast("图片保存路径："+ Constant.DOWNLOAD_PICTURE_PATH, getActivity(), 1);
            dialog.dismiss();
//            sendImage(Constant.CAMERA_PICTURE_PATH + picId);
        }
    }

    private void sendImage(String imageFilePath) {
        EMConversation conversation = EMChatManager.getInstance().getConversation(username);
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.IMAGE);
//如果是群聊，设置chattype，默认是单聊
//    message.setChatType(ChatType.GroupChat);

        ImageMessageBody body = new ImageMessageBody(new File(imageFilePath));
// 默认超过100k的图片会压缩后发给对方，可以设置成发送原图
// body.setSendOriginalImage(true);
        message.addBody(body);
        message.setReceipt(username);
        conversation.addMessage(message);
        textDialog.loadDialog();
        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
            @Override
            public void onSuccess() {
                Message msg = new Message();
                msg.what = 1;
                mHandler.sendMessage(msg);
                TipUtil.log("发送图片", "发送成功", 1);
                dialog.dismiss();
                textDialog.removeDialog();
            }

            @Override
            public void onError(int i, String s) {
                Message msg = new Message();
                msg.what = 2;
                mHandler.sendMessage(msg);
                TipUtil.log(i + "发送失败", s, 1);
                dialog.dismiss();
                textDialog.removeDialog();
            }

            @Override
            public void onProgress(int i, String s) {
                textDialog.setTvTip(i+"");
            }
        });
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        // 判断文件类型
        if (PictureBean.FILE_TYPE_SDCARD == picture.getFileType()) {
            if (!picture.getFilePath().startsWith("file://")) {
                filePath = "file://" + picture.getFilePath();
            }
        } else if (PictureBean.FILE_TYPE_ASSETS == picture.getFileType()) {
            if (!picture.getFilePath().startsWith("assets://")) {
                filePath = "assets://" + picture.getFilePath();
            }
        } else if (PictureBean.FILE_TYPE_DRAWABLE == picture.getFileType()) {
            if (!picture.getFilePath().startsWith("drawable://")) {
                filePath = "drawable://" + picture.getFilePath();
            }
        } else if (PictureBean.FILE_TYPE_CONTENT == picture.getFileType()) {
            if (!picture.getFilePath().startsWith("content://")) {
                filePath = "content://" + picture.getFilePath();
            }
        } else if (PictureBean.FILE_TYPE_NETWORK == picture.getFileType()) {
            filePath = picture.getFilePath();
        } else {
            filePath = picture.getFilePath();
        }
        filePath = picture.getFilePath();

        ImageLoader.getInstance().displayImage(filePath, mImageView, new SimpleImageLoadingListener() {
            @Override
            public void onLoadingStarted(String imageUri, View view) {
                mPprogressBar.setVisibility(View.VISIBLE);
            }

            @Override
            public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                String message = null;
                switch (failReason.getType()) {
                    case IO_ERROR:
                        message = "下载错误";
                        break;
                    case DECODING_ERROR:
                        message = "图片无法显示";
                        break;
                    case NETWORK_DENIED:
                        message = "网络有问题，无法下载";
                        break;
                    case OUT_OF_MEMORY:
                        message = "图片太大无法显示";
                        break;
                    case UNKNOWN:
                        message = "未知的错误";
                        break;
                }
                Toast.makeText(getActivity(), message, Toast.LENGTH_SHORT).show();
                mPprogressBar.setVisibility(View.GONE);
            }

            @Override
            public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                mPprogressBar.setVisibility(View.GONE);
                mAttacher.update();
            }
        });
    }

    /**
     * 创建Fragment实例
     *
     * @param picture 图片对象
     * @return
     */
    public static PictureItemFragment newInstance(PictureBean picture, String username, String shopCount) {
        final PictureItemFragment item = new PictureItemFragment();
        final Bundle args = new Bundle();
        args.putSerializable("picture", picture);
        args.putString("username", username);
        args.putString("shopCount", shopCount);
        item.setArguments(args);
        return item;
    }

//  public void setUserName(String username) {
//    this.username = username;
//  }
}
